/*
 *
 *
Copyright (c) 1998-2001 Aristar, Inc. All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

3. The end-user documentation included with the redistribution, if any,
must include the following acknowledgment:

"This product includes software developed by Aristar, Inc. (http://www.aristar.com/)."

Alternately, this acknowledgment may appear in the software itself, if and
wherever such third-party acknowledgments normally appear.

4. The names "Dialect" and "Aristar, Inc." must not be used to endorse or
promote products derived from this software without prior written permission.
For written permission, please contact info@aristar.com.

5. Products derived from this software may not be called "Dialect", nor may
"Dialect" appear in their name, without prior written permission of Aristar, Inc.

THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
ARISTAR, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

This software consists of voluntary contributions made by many individuals
on behalf of Aristar, Inc.  For more information on Aristar, Inc.,
please see <http://www.aristar.com/>.

Portions of this software are based upon software freely available and
written by individuals not associated with Aristar, Inc.  Copyrights are
maintained in the relevant source code files.
 *
 *
 */

#include "stdafx.h"
#include "CRegexModule.h"
#include "CRegExpression.h"
#include "Interpreter.h"

///////////////////////////////////
#if defined(USING_MFC) && defined(_DEBUG)
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
///////////////////////////////////

// Called by stVoid garbage collection
static void freeRegex(void* pVoid) {
	if (pVoid != NULL) {
		CRegExpression* regex = (CRegExpression*)pVoid;
		delete regex;
	}
}

CRegexImpl::CRegexImpl():CClassImpl(VALUE(), _T("regex"))
{
	m_MemberSymTab = AllocFrame(19);
	// Anything added here is static (becomes shared by all instances of the class)
	m_MemberSymTab.Set(_T("__type__"), (LPCTSTR)_T("regex"));
	m_MemberSymTab.Set(_T("__init__"), AllocFunction(__init__, _T("__core__")));
	m_MemberSymTab.Set(_T("__del__"), AllocFunction(__del__, _T("__core__")));
	m_MemberSymTab.Set(_T("match"), AllocFunction(match, _T("__core__")));
	m_MemberSymTab.Set(_T("info"), AllocFunction(group, _T("__core__")));
	m_MemberSymTab.Set(_T("string"), AllocFunction(substring, _T("__core__")));
	m_MemberSymTab.Set(_T("numsubs"), AllocFunction(numsubs, _T("__core__")));
	m_MemberSymTab.Set(_T("replace"), AllocFunction(replace, _T("__core__")));
	m_MemberSymTab.Set(_T("replacecount"), AllocFunction(replaceCount, _T("__core__")));
}

CRegexImpl::~CRegexImpl(){}

VALUE CRegexImpl::__init__(VALUE* self, int argCount, VALUE args[], CInterpreter* pInterp)
{
	ASSERT_SELF(_T("__core__"));

	CRegExpression* pRegex = new CRegExpression();
	self->Set(_T("#pRegex"), AllocVoid(pRegex, freeRegex, _T("CRegExpression")));

	int mods = 0;
	if (argCount > 1) {
		if (args[1].Type() == stString) {
			if (args[1].String().Find(_T("i")) >= 0) {
				mods = REG_ICASE;
			}
		}
		else {
			pInterp->RuntimeError(_T("If present, the second arg must be the regex modifiers string"));
			return AllocNil();
		}
	}

	if (!pRegex->Compile(args[0].String(), mods)) {
		TString error;
		switch (pRegex->GetLastErrorCode()) {
			case REG_ESPACE:
			case REG_ASSERT:
			case REG_INVARG:
				pInterp->InternalError(_T("Error generating regex: %s"), (LPCTSTR)pRegex->GetLastError());
				break;
			default:
				pInterp->RuntimeError(_T("Invalid regular expression pattern: %s"), (LPCTSTR)pRegex->GetLastError());
		}
	}

	return AllocNil();	// Return value is ignored in constructors
}

VALUE CRegexImpl::__del__(VALUE* self, int argCount, VALUE args[], CInterpreter* pInterp)
{
	ASSERT_SELF(_T("__core__"));

	// There shouldn't be any args for the destructor
	ASSERT(argCount == 0);

	// This will force garbage collection of #pRegex to occur if it
	// exists, which will call freeRegex() to close and dispose
	self->Remove(_T("#pRegex"));

	return VALUE();
}

VALUE CRegexImpl::match(VALUE* self, int argCount, VALUE args[], CInterpreter* pInterp)
{
	ASSERT_SELF(_T("__core__"));

	CRegExpression* regex = (CRegExpression*)(self->Get(_T("#pRegex")).Void());
	if (regex == NULL) {
		pInterp->RuntimeError(_T("You must contruct a regex before calling match"));
		return AllocNil();
	}
	else if ((argCount != 1) || !((args[0].Type() == stString) || (args[0].Type() == stNil))) {
		pInterp->RuntimeError(_T("regex.match() requires one string argument"));
		return AllocNil();
	}

	int offset = regex->Match(args[0].String());
	if (offset == -1) {
		// offset == -1 means no match found, but otherwise no error
		return AllocNil();
	}
	else if (offset >= 0) {
		const matchdata_t* data = regex->GetMatchData();
		if (data == NULL) return _T("");
		else return data[0].pzText;
	}
	else {
		// offset == -2 means we have a critical regexp error
		pInterp->RuntimeError(_T("regex.match(): %s"), regex->GetLastError());
		return 0;
	}
}

VALUE CRegexImpl::group(VALUE* self, int argCount, VALUE args[], CInterpreter* pInterp)
{
	ASSERT_SELF(_T("__core__"));

	CRegExpression* regex = (CRegExpression*)(self->Get(_T("#pRegex")).Void());
	if (regex == NULL) {
		pInterp->RuntimeError(_T("You must contruct a regex before calling match"));
		return AllocNil();
	}
	else if ((argCount != 1) || (args[0].Type() != stInteger)) {
		pInterp->RuntimeError(_T("regex.group() requires one integer argument"));
		return AllocNil();
	}

	int getThis = args[0].Integer();

	const matchdata_t* data = regex->GetMatchData();
	if (data == NULL) {
		pInterp->RuntimeError(_T("You must have a succesful regex.match() before regex.group()"));
		return AllocNil();
	}
	else if (getThis >= data[0].arraySize) {
		pInterp->RuntimeError(_T("regex.group() index exceeds actual number of groups in this regex"));
		return AllocNil();
	}

	VALUE result = AllocArray(2);	// [matchString, startpos, length]
	result.Set(1, data[getThis].pzText == NULL ? _T("") : data[getThis].pzText);
	result.Set(2, data[getThis].startPos + 1);
	return result;
}

VALUE CRegexImpl::substring(VALUE* self, int argCount, VALUE args[], CInterpreter* pInterp)
{
	ASSERT_SELF(_T("__core__"));

	CRegExpression* regex = (CRegExpression*)(self->Get(_T("#pRegex")).Void());
	if (regex == NULL) {
		pInterp->RuntimeError(_T("You must contruct a regex before calling substring"));
		return AllocNil();
	}
	else if ((argCount != 1) || (args[0].Type() != stInteger)) {
		pInterp->RuntimeError(_T("regex.substring() requires one integer argument"));
		return AllocNil();
	}

	int getThis = args[0].Integer();

	const matchdata_t* data = regex->GetMatchData();
	if (data == NULL) {
		pInterp->RuntimeError(_T("You must have a succesful regex.match() before regex.substring()"));
		return AllocNil();
	}
	else if (getThis >= data[0].arraySize) {
		pInterp->RuntimeError(_T("regex.substring() index exceeds actual number of substrings in this regex"));
		return AllocNil();
	}

	return data[getThis].pzText == NULL ? _T("") : data[getThis].pzText;
}

VALUE CRegexImpl::numsubs(VALUE* self, int argCount, VALUE args[], CInterpreter* pInterp)
{
	ASSERT_SELF(_T("__core__"));

	CRegExpression* regex = (CRegExpression*)(self->Get(_T("#pRegex")).Void());
	if (regex == NULL) {
		pInterp->RuntimeError(_T("You must contruct a regex before calling numsubs"));
		return AllocNil();
	}
	else if (argCount != 0) {
		pInterp->RuntimeError(_T("regex.numsubs() requires zero arguments"));
		return AllocNil();
	}

	return regex->NumberSubs();
}

VALUE CRegexImpl::replace(VALUE* self, int argCount, VALUE args[], CInterpreter* pInterp)
{
	ASSERT_SELF(_T("__core__"));

	CRegExpression* regex = (CRegExpression*)(self->Get(_T("#pRegex")).Void());
	if (regex == NULL) {
		pInterp->RuntimeError(_T("You must contruct a regex before calling replace"));
		return AllocNil();
	}
	else if ((argCount < 2) ||
		!((args[0].Type() == stString) || (args[0].Type() == stNil)) ||
		!((args[1].Type() == stString) || (args[1].Type() == stNil)))
	{
		pInterp->RuntimeError(_T("regex.replace() requires at least two string arguments"));
		return AllocNil();
	}

	int replaceCount = 0;	// Zero == replace all matches
	if (argCount >= 3) {
		if (args[2].Type() == stInteger) {
			replaceCount = args[2].Integer();
		}
		else {
			pInterp->RuntimeError(_T("The third arg to regex.replace() must be an integer"));
			return AllocNil();
		}
	}

	TString result;
	int count = regex->Replace(args[0].String(), args[1].String(), replaceCount, result);
	if (count == -1) {
		// count == -1 means we have an error
		pInterp->RuntimeError(_T("regex.replace(): %s"), regex->GetLastError());
		return AllocNil();
	}
	return result;
}

VALUE CRegexImpl::replaceCount(VALUE* self, int argCount, VALUE args[], CInterpreter* pInterp)
{
	ASSERT_SELF(_T("__core__"));

	CRegExpression* regex = (CRegExpression*)(self->Get(_T("#pRegex")).Void());
	if (regex == NULL) {
		pInterp->RuntimeError(_T("You must contruct a regex before calling replaceCount"));
		return AllocNil();
	}
	else if (argCount != 0) {
		pInterp->RuntimeError(_T("regex.replaceCount() requires zero arguments"));
		return AllocNil();
	}
	return regex->GetReplaceCount();
}
